package com.interagriculture.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.interagriculture.common.PageResult;
import com.interagriculture.entity.Data;
import com.interagriculture.entity.query.DataQuery;
import com.interagriculture.mapper.DataMapper;
import com.interagriculture.service.DataService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Data)表服务实现类
 *
 * @author makejava
 * @since 2024-10-24 19:14:05
 */
@Service("dataService")
public class DataServiceImpl implements DataService {
    @Resource
    private DataMapper dataMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param dataId 主键
     * @return 实例对象
     */
    @Override
    public Data queryById(Integer dataId) {
        return this.dataMapper.queryById(dataId);
    }

    @Override
    public Page<Data> queryByPage(Data data, PageRequest pageRequest) {
        return null;
    }

    /**
     * 新增数据
     *
     * @param data 实例对象
     * @return 实例对象
     */
    @Override
    public Data insert(Data data) {
        this.dataMapper.insert(data);
        return data;
    }

    /**
     * 修改数据
     *
     * @param data 实例对象
     * @return 实例对象
     */
    @Override
    public Data update(Data data) {
        this.dataMapper.update(data);
        return this.queryById(data.getDataId());
    }

    /**
     * 通过主键删除数据
     *
     * @param dataId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer dataId) {
        return this.dataMapper.deleteById(dataId) > 0;
    }

    /**
     * 分页查询
     * @param dataQuery
     * @return
     */
    @Override
    public PageResult findByPage(DataQuery dataQuery) {
        if(dataQuery!=null && dataQuery.getPageNum()!=null && dataQuery.getPageSize()!=null){
            PageHelper.startPage(dataQuery.getPageNum(),dataQuery.getPageSize());
        }
        if(dataQuery!=null && dataQuery.getOrderBy()!=null){
            PageHelper.orderBy(dataQuery.getOrderBy());
        }
        List<Data> dataList = dataMapper.selectByPage(dataQuery);
        PageInfo<Data> pages = new PageInfo<>(dataList);
        return new PageResult(pages.getTotal(),pages.getPages(),pages.getList());
    }

    @Override
    public void saveOrUpdate(Data data) {
        dataMapper.insertOrUpdate(data);
    }
}
